package bbs.web.control; 

import javax.servlet.http.*;

import org.apache.ibatis.session.*;
import org.apache.logging.log4j.*;
import org.springframework.stereotype.*;
import org.springframework.ui.*;
import org.springframework.web.bind.annotation.*;   

import bbs.model.User;

@Controller
public class UserController extends WebController {
	
	/**
	 * Log4j logger
	 */
	static final Logger logger = LogManager.getLogger(UserController.class);
	
	/**
	 * 회원 가입 콘트롤 
	 * @param model
	 * @param request
	 * @param userName
	 * @param passwd
	 * @param isAdmin
	 * @return
	 */
    @RequestMapping(value="/bbsUserJoin.con", method = {RequestMethod.GET, RequestMethod.POST} )
    public String doUserJoin( Model model , HttpServletRequest request ,
    		@RequestParam(value="userName", 		required=false, defaultValue="") String userName,
    		@RequestParam(value="passwd", 			required=false, defaultValue="") String passwd,
    		@RequestParam(value="passwdConfirm", 	required=false, defaultValue="") String passwdConfirm,
    		@RequestParam(value="isAdmin", 			required=false, defaultValue="false" ) Boolean isAdmin ,
    		@RequestParam(value="redirectUrl", 		required=false, defaultValue="" ) String redirectUrl 
    		) {
        
    	String viewName = null;
    	
    	logger.trace( "userName: " + userName + "; isAdmin: " + isAdmin );
    	
    	if( true ) {
    		String redirecUrlDecoded = redirectUrl;
    		try {
    			redirecUrlDecoded = WebController.getStringUrlDecoded( redirectUrl );
    		} catch ( Exception e ) { 
    		}
    		
    		logger.trace( "redirectUrl: " + redirecUrlDecoded );
    	}
    	
    	String svrMsg = "게시판에 오신 것을 환영합니다.";
    	String errMsg = "아이디를 입력하세요." ;   
    	
    	if( userName.length() < 1 ) {
    		errMsg = "아이디를 입력하세요.";
    	} else if( passwd.length() < 1 ) {
    		errMsg ="패스워드를 입력하세요.";
    	} else if( ! passwd.equals( passwdConfirm ) ) {
    		errMsg = "패스워드를 확인하세요";
    	} else { 
    		SqlSession session = bbsSystem.getSqlSession();  
    		
    		// 이전 사용자 존재 여부 조회 
    		User prevUser = bbsSystem.getUser(session, userName);
    		
    		if( prevUser != null ) {
    			errMsg = "같은 이름의 사용자가 있습니다.";
    		} else if( prevUser == null ) { 
	    		int updCnt = bbsSystem.createNewUser( request, session, userName, passwd, isAdmin ); 
	    		session.close();
	    		
	    		if( updCnt > 0 ) {
	    			viewName = "redirect:bbsUserLogin.con" + "?" + "newUserCreated=true" ;
	    		} else if( updCnt < 0 ) {
	    			errMsg = "사용자를 생성할 수 없습니다.";
	    		}
    		}
    	} 
    	
    	model.addAttribute( "userName" , 	userName 	); 
    	model.addAttribute( "passwd", 		"" 			); 
    	model.addAttribute( "isAdmin" , 	isAdmin 	);   
    	
    	model.addAttribute( "svrMsg", 		svrMsg 		);
    	model.addAttribute( "errMsg", 		errMsg 		);  
        
    	if( viewName == null ) {
    		viewName = "bbs_user_join.html" ;
    	} 
        
        return viewName;
    }

	/**
	 * 로그인 화면
	 * @param model
	 * @param request
	 * @param userName
	 * @param passwd
	 * @param isAdmin
	 * @return
	 */
    @RequestMapping(value="/bbsUserLogin.con", method = {RequestMethod.GET, RequestMethod.POST} )
    public String doUesrLogin( Model model , HttpServletRequest request ,
    		@RequestParam(value="userName", required=false, defaultValue="") String userName,
    		@RequestParam(value="passwd", required=false, defaultValue="") String passwd,
    		@RequestParam(value="isAdmin", required=false, defaultValue="false" ) Boolean isAdmin ,
    		@RequestParam(value="newUserCreated", required=false, defaultValue="false" ) Boolean newUserCreated ,
    		@RequestParam(value="redirectUrl", 		required=false, defaultValue="" ) String redirectUrl 
    		) {
        
    	logger.trace( "userName: " + userName + "; isAdmin: " + isAdmin );
    	
    	if( true ) {
    		String redirecUrlDecoded = redirectUrl;
    		try {
    			redirecUrlDecoded = WebController.getStringUrlDecoded( redirectUrl ) ;
    		} catch ( Exception e ) { 
    		}
    		
    		logger.trace( "redirectUrl: " + redirecUrlDecoded );
    	}
    	
    	String svrMsg = "게시판에 오신 것을 환영합니다.";
    	String errMsg = "아이디를 입력하세요." ;  
    	
    	boolean loginOk = false;
    	
    	if( newUserCreated ) {
    		svrMsg = "회원 가입을 축하합니다." ;
    		userName = "";
    		passwd = "";
    		isAdmin = false;
    	} else if( userName.length() < 1 ) {
    		errMsg = "아이디를 입력하세요.";
    	} else if( passwd.length() < 1 ) {
    		errMsg ="패스워드를 입력하세요.";
    	} else { 
    		SqlSession session = bbsSystem.getSqlSession();  
    		User loginUser = bbsSystem.doLogin( request, session, userName, passwd, isAdmin ); 
    		session.close();
    		
    		if( loginUser == null ) { 
    			// 패스워드가 틀렸을 때,
    			errMsg = "사용자 정보가 없습니다." ;
    		} else if( ! loginUser.isLoginSucess() ) { 
    			errMsg = "사용자 정보가 없습니다." ;
    		} else if(  isAdmin ) {
    			if( ! loginUser.isAdmin() ) {
    				errMsg ="관리자 권한이 없습니다." ;
    			} else if( loginUser.isAdmin() ){ 
    				loginOk = true; 
    				this.loginAdminOnTheSession(request);
    				svrMsg = "관리자 로그인 성공" ;
    			}
    		} else {
    			loginOk = true;
    			svrMsg = "로그인 성공" ;
    		}
    	}
    	
    	if( loginOk ) {  
    		errMsg = null ;
    	}
    	
    	model.addAttribute( "userName" , 	userName 	); 
    	model.addAttribute( "passwd", 		"" 			); 
    	model.addAttribute( "isAdmin" , 	isAdmin 	);  
    	model.addAttribute( "loginOk" , 	loginOk 	); 
    	model.addAttribute( "redirectUrl", 	redirectUrl );
    	
    	model.addAttribute( "svrMsg", 		svrMsg 		);
    	model.addAttribute( "errMsg", 		errMsg 		); 
    	
    	if( loginOk ) {
    		if( isAdmin ) {
    			
    		} 
    		
    		redirectUrl = redirectUrl == null ? null : redirectUrl.trim();
    		
    		if( redirectUrl != null && redirectUrl.length() > 0 ) {
    			String recirectUrlDecoded = WebController.getStringUrlDecoded( redirectUrl );
    			
    			return "redirect:" + recirectUrlDecoded ;
    		} else { 
    			return "redirect:bbsBoardList.con";  
    		}
    	}
        
        return "bbs_user_login.html"; 
    }
    
    /**
     * 로그아웃 화면
     * @param request
     * @return
     */
    @RequestMapping(value="/bbsUserLogout.con", method = {RequestMethod.GET, RequestMethod.POST} )
    public String doUerLogout( HttpServletRequest request ) { 
    	
    	this.bbsSystem.doLogout( request );
    	
    	this.logoutAdminOnTheSession(request);
    	
    	return "redirect:bbsUserLogin.con";
    }

}